
//
//  DefaultViewController.m
//  HJZWeiBo
//
//  Created by 蒋晨成 on 16/5/27.
//  Copyright © 2016年 蒋晨成. All rights reserved.
//

#import "DefaultViewController.h"
#import "RequestManager.h"
#import "UIImage+Extend.h"
#import "HJZStatus.h"
#import "HJZStatusFrame.h"
#import "AppDelegate.h"
#import "HJZStatusTableViewCell.h"
#import <MJRefresh.h>
#import "UIBarButtonItem+Extend.h"
#import "HJZStatusContentViewController.h"
#import "HCScanQRViewController.h"
#import "MeDefaultViewController.h"
#import "WeiboUser.h"
#import "HJZUploadViewController.h"

@interface DefaultViewController ()< WBHttpRequestDelegate, UITableViewDelegate, UITableViewDataSource, RequestDelegate, HJZRetweenStatusViewDelegate, HJZStatusTopViewDelegate, HJZStatusToolBarDelegate>


@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSString *since_id;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, strong) UIView *bgView;



@end

@implementation DefaultViewController



#pragma mark --- 微博SDK请求用户信息 ---
- (void)requestForUserProfileWithUserName:(NSString *)name
{
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
   
    
    
    [WBHttpRequest requestForUserProfile:nil withAccessToken:accessToken andOtherProperties:@{@"screen_name":name} queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        
        WeiboUser *user = (WeiboUser *)result;
       
        MeDefaultViewController *meDefaultVC = [[MeDefaultViewController alloc] init];
        meDefaultVC.user = user;
        [self.navigationController pushViewController:meDefaultVC animated:YES];
        
    }];
}



- (void)destoryStatusWithID:(NSString *)statusID {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];

    [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/statuses/destroy.json" httpMethod:@"POST" params:@{@"access_token":accessToken,@"id":statusID} delegate:self withTag:@"删除微博"];
}
- (void)requestStatusData {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    if (!accessToken) {
        return;
    }
    NSString *page = [NSString stringWithFormat:@"%ld", _page];
    [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/statuses/friends_timeline.json" httpMethod:@"GET" params:@{@"access_token":accessToken,@"page":page,@"since_id":_since_id} delegate:self withTag:@"微博"];
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data {
     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([request.tag isEqualToString:@"微博"]) {
        NSArray *statuses = dic[@"statuses"];
        if (statuses.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        if (_page == 1) {
            [_dataSource removeAllObjects];
            
        }
        for (NSDictionary *statusDic in statuses) {
            HJZStatus *status = [[HJZStatus alloc] init];
            [status setValuesForKeysWithDictionary:statusDic];
            HJZStatusFrame *statusFrame = [[HJZStatusFrame alloc] init];
            statusFrame.status = status;
            [_dataSource addObject:statusFrame];
            
        }
        self.tableView.mj_header.hidden = NO;
        self.tableView.mj_footer.hidden = NO;
        [self.tableView reloadData];
  
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
    }else if ([request.tag isEqualToString:@"赞微博"]) {
        [self alertWithText:dic[@"error"]];
    }else if (@"删除微博") {
        [self alertWithText:@"删除成功"];
        [self deleteDataWithIndesPath:_indexPath];
    }
   
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    [self bgViewIsHidden];
 
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    UIBarButtonItem *rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(rightBarButtonAction:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    UIBarButtonItem *leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_profile_edit" highImageName:@"navigationbar_profile_edit_highlighted" target:self action:@selector(leftBarButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    self.since_id = @"0";
    self.page = 1;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.since_id = @"0";
        [self requestStatusData];
        
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        self.since_id = [_dataSource.lastObject status].created_at;
        [self requestStatusData];
    }];
    self.tableView.mj_header.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    self.dataSource = [NSMutableArray array];
   
    self.bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bgView];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth / 2, kWidth /2)];
    imageView.center = CGPointMake(kWidth / 2, kHeight /2);
    imageView.image = [UIImage imageNamed:@"tabbar_home"];
    [self.bgView addSubview:imageView];
    
    [self bgViewIsHidden];
    
    [self requestStatusData];
    
    
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.myDelegate = self;

    
    
    
    
   

  
    
   
}

- (void)rightBarButtonAction:(UIBarButtonItem *)barButton {
   
    
    HCScanQRViewController *scan = [[HCScanQRViewController alloc]init];
    //调用此方法来获取二维码信息
    [scan successfulGetQRCodeInfo:^(NSString *QRCodeInfo) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.detailTextLabel.text = QRCodeInfo;
    }];
    [self.navigationController pushViewController:scan animated:YES];
}



- (void)leftBarButtonAction:(UIBarButtonItem *)barButton {
   
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HJZStatusTableViewCell *cell = [HJZStatusTableViewCell cellWithTableView:tableView];
    cell.topView.retweetView.delegate = self;
    cell.topView.delegate = self;
    cell.statusToolBar.delegate = self;
    cell.statusFrame = self.dataSource[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.dataSource[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJZStatusContentViewController *statusContentVC = [[HJZStatusContentViewController alloc] init];
    statusContentVC.statusFrame = _dataSource[indexPath.row];
    [self.navigationController pushViewController:statusContentVC animated:YES];

}

- (void)requestAttitudeStatus:(NSString *)statusID {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/attitudes/create.json" httpMethod:@"POST" params:@{@"access_token":accessToken,@"id":statusID} delegate:self withTag:@"赞微博"];
}



- (void)alertWithText:(NSString *)text {

    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:text message:nil preferredStyle:UIAlertControllerStyleAlert];
    [self.navigationController presentViewController:alertVC animated:YES completion:^{
        [self performSelector:@selector(delayAction:) withObject:alertVC afterDelay:1];
    }];
}

- (void)delayAction:(UIAlertController *)alertVC {
    [alertVC dismissViewControllerAnimated:YES completion:nil];
}





#pragma mark ---删除微博
- (void)statusTopViewDeleteWithStatus:(HJZStatus *)status WithCell:(UITableViewCell *)cell {
      NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    UIAlertController *actionVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    if ([status.user.idstr isEqualToString:userID]) {
        
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self destoryStatusWithID:status.idstr];
            
            self.indexPath = indexPath;
            
        }];
        [actionVC addAction:deleteAction];
        
    }else {
        UIAlertAction *followAction = [UIAlertAction actionWithTitle:@"关注" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [actionVC addAction:followAction];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [actionVC addAction:cancelAction];
    [self.navigationController presentViewController:actionVC animated:YES completion:nil];

    
}

- (void)deleteDataWithIndesPath:(NSIndexPath *)indexPath {
    [self.dataSource removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}

#pragma mark -- 登录成功
- (void)requestReceiveWithState:(NSInteger)state {
    if (state == 0) {
        [self requestStatusData];
    }
}


- (void)bgViewIsHidden {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    if (!accessToken) {
        self.bgView.hidden = NO;
        return;
    }else {
        self.bgView.hidden = YES;
    }
}


#pragma mark -转发微博视图的代理方法 （RCLabel）
- (void)retweenStatusViewClickWithUrl:(NSString *)url {

    [self getRClabelWithUrl:url];
}

#pragma mark -微博的代理方法
- (void)statusTopViewClickWithUrl:(NSString *)url {
    [self getRClabelWithUrl:url];
}


/**
 *  RCLabel
 */
- (void)getRClabelWithUrl:(NSString *)url{
    NSString *content = url;
    if ([content hasPrefix:@"@"]) {
        content = [content stringByReplacingOccurrencesOfString:@"@" withString:@""];
        
        [self requestForUserProfileWithUserName:content];
        
    }else if ([content hasPrefix:@"#"]) {
        content = [content stringByReplacingOccurrencesOfString:@"#" withString:@""];
    }else if ([content hasPrefix:@"http"]){
        NSLog(@"%@",url);
        NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
        NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
        NSLog(@"%@", accessToken);
        NSLog(@"%@", userID);
    }
}

#pragma mark -微博代理方法 tap


- (void)statusTopViewTapWithRetweenStatus:(HJZStatus *)status {
    HJZStatusFrame *statusFrame = [[HJZStatusFrame alloc] init];
    statusFrame.status = status;
    HJZStatusContentViewController *statusContentVC = [[HJZStatusContentViewController alloc] init];
    statusContentVC.statusFrame = statusFrame;
    [self.navigationController pushViewController:statusContentVC animated:YES];
}
#pragma mark -微博代理方法 点击昵称
- (void)statusTopViewClickWithName:(NSString *)name {
    [self requestForUserProfileWithUserName:name];
}

#pragma mark ---点击工具栏的代理
- (void)statusToolBarClickWithButtonType:(NSInteger)tag status:(HJZStatus *)status {
    if (tag == 3) {
        
        [self requestAttitudeStatus:status.idstr];
    }
    if (tag == 2) {
        if (status.comments_count != 0) {
            HJZStatusFrame *statusFrame = [[HJZStatusFrame alloc] init];
            statusFrame.status = status;
            HJZStatusContentViewController *statusContentVC = [[HJZStatusContentViewController alloc] init];
            statusContentVC.statusFrame = statusFrame;
            [self.navigationController pushViewController:statusContentVC animated:YES];
        }else {
           
            HJZUploadViewController *uploadVC = [[HJZUploadViewController alloc] init];
            uploadVC.status = status;
            uploadVC.uploadType = UploadTypeComment;
            UINavigationController *createCommentNav = [[UINavigationController alloc] initWithRootViewController:uploadVC];
            
            [self.navigationController presentViewController:createCommentNav animated:YES completion:nil];
        }
    }
    if (tag == 1) {
        HJZUploadViewController *uploadVC = [[HJZUploadViewController alloc] init];
        uploadVC.status = status;
        uploadVC.uploadType = UploadTypeRetween;
        UINavigationController *createCommentNav = [[UINavigationController alloc] initWithRootViewController:uploadVC];
        
        [self.navigationController presentViewController:createCommentNav animated:YES completion:nil];
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
